package com.example.lcpharmacy.lcutils.intercepter;

import com.example.lcpharmacy.entity.UserEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashSet;
import java.util.Set;

@Component
public class AuthIntercepter implements HandlerInterceptor {

    private static final Set<String> NOT_INTERCEPT_URI = new HashSet<>();//不拦截的URI

    static {
        NOT_INTERCEPT_URI.add("user/login.html");
    }

    /**
    * 在请求处理之前进行调用（Controller方法调用之前）
    */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        System.out.println("uri："+uri);
        if(NOT_INTERCEPT_URI.contains(uri)){
            //不拦截
            return true;
        }
        UserEntity user = (UserEntity) request.getSession().getAttribute("currentUser");
        if(user!=null){
            response.sendRedirect("../user/login.html");
        }
        System.out.println("拦截："+uri);
        response.sendRedirect("../user/login.html");
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }


    /**
     * 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }


    /**
     * 在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行
     * （主要是用于进行资源清理工作）
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
